﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Sunimage.Spjg.Common;

namespace Sunimage.Spjg.DAL
{
    public class FileDa
    {

        /// <summary>
        /// Insert
        /// </summary>
        /// <param name="file"></param>
        public static void Insert(DiskFile file)
        {
            Database db = DBHelper.GetDatabase();
            object[] pars = new object[]
            {
                file.Id,
                file.Title,
                file.Path,
                file.UploadTime,
                file.Remark,
                file.OwnerId,
                file.IsShared
            };
            try
            {
                db.ExecuteNonQuery("Usp_InsertFile", pars);
            }
            catch (System.Data.SqlClient.SqlException sex)      // 只捕获SqlException，其余抛出继续传播
            {
                DBHelper.ParseSqlException(sex, false);
            }
        }
        public static void Update(DiskFile file)
        {
            Database db = DBHelper.GetDatabase();
            object[] pars = new object[]
            {
                file.Id,
                file.Title,
                file.Path,
                file.UploadTime,
                file.Remark,
                file.OwnerId,
                file.IsShared
            };
            db.ExecuteNonQuery("Usp_UpdateFile", pars);
        }

        public static void Delete(Guid id)
        {
            Database db = DBHelper.GetDatabase();

            db.ExecuteNonQuery("Usp_DeleteFile", id);
        }

        public static List<DiskFile> GetAll()
        {
            Database db = DBHelper.GetDatabase();
            List<DiskFile> files = new List<DiskFile>();
            IDataReader dataReader = null;

            dataReader = db.ExecuteReader("Usp_GetFileList");

            using (dataReader)
            {
                while (dataReader.Read())
                {
                    files.Add(Populate(dataReader));
                }
            }

            return files;
        }

        private static DiskFile Populate(IDataReader dataReader)
        {

            DiskFile file = new DiskFile();
            file.Id = dataReader.GetGuid(0);
            file.Title = dataReader.GetString(1);
            file.Path = dataReader.GetString(2);
            file.UploadTime = dataReader.GetDateTime(3);
            file.Remark = dataReader.IsDBNull(4) ? "" : dataReader.GetString(4);
            file.OwnerId = dataReader.GetInt32(5);
            file.IsShared = dataReader.GetBoolean(6);

            return file;
        }
    }
}
